// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成
package com.fowo.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.common.model.IdListPo;
import com.fowo.api.common.model.IdPo;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.R;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.Receipt;
import com.fowo.api.model.receipt.ReceiptImportPo;
import com.fowo.api.model.receipt.ReceiptItemVo;
import com.fowo.api.model.receipt.ReceiptQuerySubtableParam;
import com.fowo.api.model.receipt.ReceiptQuerySubtableResult;
import com.fowo.api.model.receipt.ReceiptSearchParamPo;
import com.fowo.api.model.receipt.ReceiptVo;
import com.fowo.api.service.ReceiptService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.user.model.JwtUserInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StreamUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "收货单")
@RequestMapping("/api/receipt")
@RestController
public class ReceiptController {

  @Resource
  private ReceiptService service;

  @Operation(summary = "查询结果")
  @GetMapping
  public R<List<ReceiptItemVo>> search(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(service.search(search));
  }

  @Operation(summary = "快速查询选项(有缓存)")
  @GetMapping("options")
  public R<List<OptionItem<ReceiptItemVo>>> searchOptions(
    ReceiptSearchParamPo search
  ) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(service.searchOptions(search));
  }

  @Operation(summary = "查询最后更新时间")
  @GetMapping("lastUpdateTime")
  public R<Date> searchLastUpdateTime(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(service.searchLastUpdateTime(search));
  }

  @Operation(summary = "获取分页查询结果")
  @GetMapping("page")
  public R<Page<ReceiptItemVo>> getPage(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(service.pageSearch(search));
  }

  @Operation(summary = "获取包括子表的查询结果")
  @GetMapping("page-with-child")
  public R<Page<?>> getPageWithChild(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(service.pageWithChildSearch(search));
  }

  @Operation(summary = "仅获取子表的查询结果")
  @GetMapping("page-only-child/{parentId}")
  public R<Page<?>> getPageOnlyChild(
    @PathVariable Long parentId,
    ReceiptSearchParamPo search
  ) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(service.pageOnlyChildSearch(parentId, search));
  }

  @Operation(summary = "查询是否后台下载")
  @GetMapping("getBackgroundExportFlag")
  public R<Boolean> getBackgroundExportFlag(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(service.getBackgroundExportFlag(search));
  }

  @Operation(summary = "获取详情")
  @GetMapping("{id}")
  public R<ReceiptVo> getVoById(@PathVariable Long id) {
    return R.data(() -> service.getVoById(id));
  }

  @Operation(summary = "获取收货单号相关的编号列表")
  @GetMapping("order-sn/{texts}/ids")
  public R<List<Long>> getIdsByOrderSn(@PathVariable String texts) {
    List<String> nameList = Arrays
      .stream(texts.split(","))
      .collect(Collectors.toList());
    return R.data(() -> service.getIdsByOrderSn(nameList));
  }

  @Operation(summary = "获取编号相关的收货单号列表")
  @GetMapping("order-sn/{ids}")
  public R<List<String>> getVoById(@PathVariable String ids) {
    List<Long> idList = Arrays
      .asList(ids.split(","))
      .stream()
      .map(Long::valueOf)
      .collect(Collectors.toList());
    return R.data(() -> service.getOrderSnByIds(idList));
  }

  @PreAuthorize("@am.canAccess('receiptCreate')")
  @Operation(summary = "新增")
  @PostMapping
  public R<Long> create(@Validated @RequestBody ReceiptVo model) {
    return R.data(() -> service.create(model));
  }

  @PreAuthorize("@am.canAccess('receiptEdit')")
  @Operation(summary = "更新")
  @PutMapping
  public R update(@RequestBody ReceiptVo model) {
    return R.run(() -> service.update(model));
  }

  @PreAuthorize("@am.canAccess('receiptEdit')")
  @Operation(summary = "编辑更新")
  @PutMapping("edit")
  public R updateForEdit(@RequestBody ReceiptVo model) {
    return R.run(() -> service.updateForEdit(model));
  }

  @PreAuthorize("@am.canAccess('receiptDelete')")
  @Operation(summary = "删除")
  @DeleteMapping("{id}")
  public R delete(@PathVariable Long id) {
    return R.run(() -> service.delete(id));
  }

  @PreAuthorize("@am.canAccess('receiptDelete')")
  @Operation(summary = "批量删除")
  @DeleteMapping("batch")
  public R batchDelete(@RequestBody IdListPo po) {
    return R.run(() -> service.batchDelete(po.getIds()));
  }

  @PreAuthorize("@am.canAccess('receiptImport')")
  @Operation(summary = "导入预览")
  @PostMapping("import-preview")
  public R<List<ImportRow<ReceiptImportPo>>> importPreview(
    @RequestBody SysFile sysFile,
    @RequestParam(name = "template", required = false) Long templateId,
    @RequestParam(
      name = "allowOverrides",
      defaultValue = "false"
    ) boolean allowOverrides
  ) {
    return R.data(() ->
      service.importPreview(sysFile, templateId, allowOverrides)
    );
  }

  @PreAuthorize("@am.canAccess('receiptImport')")
  @Operation(summary = "完成导入")
  @PostMapping("import-done")
  public R importDone(
    @RequestBody List<ImportRow<ReceiptImportPo>> rows,
    @RequestParam(name = "template", required = false) Long templateId
  ) {
    return R.run(() -> service.importDone(rows, templateId));
  }

  @Operation(summary = "下载导入模版")
  @GetMapping("import/template")
  public void downloadImportTemplate(HttpServletResponse response)
    throws IOException {
    ResponseUtils.setAttachmentFileName(response, "收货单导入模版.xlsx");
    InputStream inputStream = new ClassPathResource("templates/Receipt.xlsx")
      .getInputStream();
    StreamUtils.copy(inputStream, response.getOutputStream());
  }

  @Operation(summary = "导出")
  @GetMapping("export")
  @PreAuthorize("@am.canAccess('receiptExport')")
  public void export(
    @RequestParam(name = "template", required = false) Long templateId,
    ReceiptSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    service.export(templateId, search, response);
  }

  @PreAuthorize("@am.canAccess('receiptPrintProductBarCodesCustom')")
  @Operation(summary = "打印产品条码（自定义）")
  @PostMapping("printProductBarCodesCustom")
  public R printProductBarCodesCustom(@RequestBody IdPo po) {
    return R.run(() -> service.printProductBarCodesCustom(po.getId()));
  }

  @PreAuthorize("@am.canAccess('receiptPrintProductBarCodesTemplate')")
  @Operation(summary = "打印产品条码（模版）")
  @PostMapping("printProductBarCodesTemplate")
  public R printProductBarCodesTemplate(@RequestBody IdPo po) {
    return R.run(() -> service.printProductBarCodesTemplate(po.getId()));
  }

  @PreAuthorize("@am.canAccess('receiptImportAndReceive')")
  @Operation(summary = "导入收货")
  @PostMapping("importAndReceive")
  public R importAndReceive(@RequestBody IdListPo po) {
    return R.run(() -> service.importAndReceive(po.getIds()));
  }

  @PreAuthorize("@am.canAccess('receiptImportShortcutToLibrary')")
  @Operation(summary = "导入快捷入库")
  @PostMapping("importShortcutToLibrary")
  public R importShortcutToLibrary(@RequestBody IdListPo po) {
    return R.run(() -> service.importShortcutToLibrary(po.getIds()));
  }

  /**
   * 视图选项卡标题上显示计数
   */
  @Operation(summary = "视图选项卡标题上显示计数")
  @GetMapping("getTabHeaderShowTotal")
  public R<Map> getTabHeaderShowTotal() {
    return R.data(() -> service.getTabHeaderShowTotal());
  }

  @Operation(summary = "全部")
  @GetMapping("all-1")
  public R<List<ReceiptItemVo>> all1(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(() -> service.all1(search));
  }

  @Operation(summary = "全部分页")
  @GetMapping("all-1Page")
  public R<Page<ReceiptItemVo>> all1Page(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(() -> service.all1Page(search));
  }

  @Operation(summary = "全部包括子表的查询结果")
  @GetMapping("all-1Page-with-child")
  public R<Page<?>> all1PageWithChild(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(service.all1PageWithChildSearch(search));
  }

  @Operation(summary = "全部最后更新时间")
  @GetMapping("all-1LastUpdateTime")
  public R<Date> all1LastUpdateTime(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(() -> service.all1LastUpdateTime(search));
  }

  @Operation(summary = "待收货")
  @GetMapping("wait-for-receiving")
  public R<List<ReceiptItemVo>> waitForReceiving(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(() -> service.waitForReceiving(search));
  }

  @Operation(summary = "待收货分页")
  @GetMapping("wait-for-receivingPage")
  public R<Page<ReceiptItemVo>> waitForReceivingPage(
    ReceiptSearchParamPo search
  ) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(() -> service.waitForReceivingPage(search));
  }

  @Operation(summary = "待收货包括子表的查询结果")
  @GetMapping("wait-for-receivingPage-with-child")
  public R<Page<?>> waitForReceivingPageWithChild(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(service.waitForReceivingPageWithChildSearch(search));
  }

  @Operation(summary = "待收货最后更新时间")
  @GetMapping("wait-for-receivingLastUpdateTime")
  public R<Date> waitForReceivingLastUpdateTime(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(() -> service.waitForReceivingLastUpdateTime(search));
  }

  @Operation(summary = "已完成")
  @GetMapping("done")
  public R<List<ReceiptItemVo>> done(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(() -> service.done(search));
  }

  @Operation(summary = "已完成分页")
  @GetMapping("donePage")
  public R<Page<ReceiptItemVo>> donePage(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(() -> service.donePage(search));
  }

  @Operation(summary = "已完成包括子表的查询结果")
  @GetMapping("donePage-with-child")
  public R<Page<?>> donePageWithChild(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(service.donePageWithChildSearch(search));
  }

  @Operation(summary = "已完成最后更新时间")
  @GetMapping("doneLastUpdateTime")
  public R<Date> doneLastUpdateTime(ReceiptSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo != null) {
      search.setCurrentUserId(jwtUserInfo.getUserId());
    }
    return R.data(() -> service.doneLastUpdateTime(search));
  }

  @Operation(summary = "更新收货单的状态为1")
  @PostMapping("updateReceiptStatusToFinished")
  public R<?> updateReceiptStatusToFinished(@RequestBody JSONObject param) {
    return R.data(() -> service.updateReceiptStatusToFinished(param));
  }

  @Operation(summary = "质检按钮更新数据")
  @PutMapping("checkButtonUpdatesData")
  public R<?> checkButtonUpdatesData(@RequestBody JSONObject param) {
    return R.data(() -> service.checkButtonUpdatesData(param));
  }

  @Operation(summary = "收货单收货按钮")
  @PutMapping("receiptReceiptButton")
  public R<?> receiptReceiptButton(@RequestBody JSONObject param) {
    return R.data(() -> service.receiptReceiptButton(param));
  }

  @Operation(summary = "快捷入库")
  @PutMapping("quickStorage")
  public R<?> quickStorage(@RequestBody JSONObject param) {
    return R.data(() -> service.quickStorage(param));
  }

  @Operation(summary = "查询子表")
  @GetMapping("querySubtable")
  public R<List<ReceiptQuerySubtableResult>> querySubtable(
    ReceiptQuerySubtableParam param
  ) {
    return R.data(() -> service.querySubtable(param));
  }

  @Operation(summary = "关联单据（入库单）")
  @PostMapping("relatedDocuments")
  public R<?> relatedDocuments(@RequestBody JSONObject param) {
    return R.data(() -> service.relatedDocuments(param));
  }

  @Operation(summary = "查询子表数据")
  @PostMapping("querySubtableData")
  public R<?> querySubtableData(@RequestBody JSONObject param) {
    return R.data(() -> service.querySubtableData(param));
  }

  @Operation(summary = "关联单据（质检单）")
  @PostMapping("relatedDocumentsQqualityInspectionForm")
  public R<?> relatedDocumentsQqualityInspectionForm(
    @RequestBody JSONObject param
  ) {
    return R.data(() -> service.relatedDocumentsQqualityInspectionForm(param));
  }

  @Operation(summary = "免检")
  @PostMapping("exemptedInspection")
  public R<?> exemptedInspection(@RequestBody JSONObject param) {
    return R.data(() -> service.exemptedInspection(param));
  }
}
